﻿using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using MS.Data.API.Read.Command;
using MS.Data.Domain;
using MS.Data.ErrorCode;
using MS.Data.Infratructrue.Istanbul;
using System.IdentityModel.Tokens.Jwt;
using System.Text;

namespace MS.Data.API.Read.CommandHandle
{
    /// <summary>
    /// 登录查询命令处理
    /// </summary>
    public class LoginCommandHandle : IRequestHandler<LoginCommand, APIResult<UserDto>>
    {
        /// <summary>
        /// 用户
        /// </summary>
        IBaseRepository<Domain. User> userRep;
        /// <summary>
        /// 角色用户
        /// </summary>
        IBaseRepository<RoleUser> roleUserRep;
        /// <summary>
        /// 角色
        /// </summary>
        IBaseRepository<Domain.Role> roleRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRep">用户</param>
        /// <param name="roleRep">角色</param>
        public LoginCommandHandle(IBaseRepository<Domain.User> userRep, IBaseRepository<Domain.Role> roleRep, IBaseRepository<RoleUser> roleUserRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.roleUserRep = roleUserRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public Task<APIResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDto> result = new APIResult<UserDto>();
            result.code = APIEnum.登录成功;
            result.mes = APIEnum.登录成功.ToString();

            var list = from a in userRep.GetAll()
                       join b in roleUserRep.GetAll() on a.UserId equals b.UserId
                       join c in roleRep.GetAll() on b.RoleId equals c.RoleId
                       where a.UserName==request.UserName
                       select new UserDto()
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           UserPwd= a.UserPwd,
                           NickName=a.NickName,
                           Phone=a.Phone,
                           RoleId=b.RoleId,
                           RUId=b.RUId,
                           RoleName=c.RoleName,
                       };

            var enlint = list.FirstOrDefault();
            if (enlint == null)
            {
                result.code = APIEnum.登录失败;
                result.mes = APIEnum.登录失败.ToString()+"用户名不存在";
                return Task.FromResult(result);
            }
            var mi = request.UserPwd.GetMD5();
            if (enlint.UserPwd != mi)
            {
                result.code = APIEnum.登录失败;
                result.mes = APIEnum.登录失败.ToString()+"用户名或者密码不匹配";
                return Task.FromResult(result);
            }
            result.data = enlint;
            result.Token = CreateTokenString();

            return Task.FromResult(result);
        }
        /// <summary>/// 生成 JWT Token（令牌）/// </summary>/// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
